package com.epfresh.supplier.activity;

import android.content.DialogInterface;
import android.content.Intent;

import android.os.Bundle;
import android.text.InputFilter;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.epfresh.api.entity.RequestEntitySupply;
import com.epfresh.api.entity.ResponseEntity;

import com.epfresh.supplier.dialog.MinusInfoDialog;
import com.epfresh.supplier.entity.MinusDialogInfo;
import com.epfresh.api.global.BaseActivity;

import com.epfresh.api.http.OnRequestListener;
import com.epfresh.api.utils.CashierInputFilter;
import com.epfresh.api.utils.L;
import com.epfresh.api.utils.T;
import com.epfresh.api.widget.CommonInputItem;
import com.epfresh.pickerview.dialog.WheelDialog;
import com.epfresh.supplier.R;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.util.ArrayList;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class OrderMinusActivity extends BaseActivity {

    static final String TAG = "OrderMinusActivity";

    CommonInputItem ciReason;
    EditText etMoney,etNumber, etDetail;
    TextView tvSure,tvHint,tvUnit,tvNumberHint;
    String id;

    String jmtAppleReasonType="2",jmtProductCount,jmtApplyReasonDetails,jmtPrice;

    String costSum;
    String productNumber="0";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initView();
        id = getIntent().getStringExtra("id");
        if(id!=null){

            tvUnit.setText(getIntent().getStringExtra("saleUnit"));
            costSum = getIntent().getStringExtra("costSum");
            if(getIntent().getStringExtra("productNumber")!=null){
                productNumber = getIntent().getStringExtra("productNumber");
            }
            tvHint.setText("最高可输入退款金额"+costSum+"元");
            tvNumberHint.setText("可退货"+productNumber+getIntent().getStringExtra("saleUnit"));

        }else {
            T.toast("没收到订单号");
            finish();
        }

    }
    void initView(){
        setContentView(R.layout.activity_order_minus);
        ciReason = (CommonInputItem)findViewById(R.id.ci_reason);
        setToolbarTitle("减免退");
        ciReason.setOnClickListener(this);
        etMoney = (EditText)findViewById(R.id.et_money);
        etNumber = (EditText)findViewById(R.id.et_number);
        etDetail = (EditText)findViewById(R.id.et_detail);
        tvSure = (TextView)findViewById(R.id.tv_sure);
        tvHint = (TextView)findViewById(R.id.tv_money_hint);
        tvNumberHint = (TextView)findViewById(R.id.tv_number_hint);
        tvUnit = (TextView)findViewById(R.id.tv_inventory);
        etMoney.setFilters(new InputFilter[]{new CashierInputFilter()});
        etNumber.setFilters(new InputFilter[]{new CashierInputFilter()});

        tvBack.setVisibility(View.VISIBLE);
        baseback.setVisibility(View.VISIBLE);
        ciReason.setOnClickListener(this);
        tvSure.setOnClickListener(this);
    }

    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.baseback:
                // 返回上一页
                finish();
                break;

            case R.id.ci_reason:
                selectReason();
                break;
            case R.id.tv_sure:
                if(isWindowLocked())
                    return;
                else
                    post();
                break;
        }
    }

    @Override
    public void onBackPressed() {
        Log.e("justtry","finish");
        finish();
        super.onBackPressed();
    }

    String cmdSave = "appOrder/jmtSave";
    private void post(){
        if(ciReason.getTitleText().equals("请选择减免原因")){
            T.toast("请选择减免原因");
            return;
        }
        if(etMoney.getText().toString().equals("")){
            T.toast("请输入减免金额");
            return;
        }
        if(Double.parseDouble(etMoney.getText().toString())==0){
            T.toast("减免金额不能为0，请重新输入");
            return;
        }
        if(etMoney.getText().toString().equals("")||Double.parseDouble(etMoney.getText().toString())>Double.parseDouble(costSum)){
            T.toast("金额有误");
            return;
        }
        if(!TextUtils.isEmpty(etNumber.getText())) {
            if (Double.parseDouble(etNumber.getText().toString()) > Double.parseDouble(productNumber)) {
                T.toast("数量有误");
                return;
            }
        }
/*        if(jmtAppleReasonType.equals("1")){
            if(etNumber.getText().toString().equals("")||Double.parseDouble(etNumber.getText().toString())>Double.parseDouble(productNumber)){
                T.toast("数量有误");
                return;
            }
        }*/
       // T.toast(id+"____________"+etMoney.getText().toString()+"____________"+etNumber.getText().toString()+"____________"+jmtAppleReasonType+"____________"+etDetail.getText().toString());
        RequestEntitySupply<Map<String, String>> data = new RequestEntitySupply<>();
        data.setCmd(com.epfresh.api.constant.AppSupplyRouterConstant.cmd_order_supplier_jmt_save);
        Map<String, String> map = new HashMap<>();
        map.put("supplyId", getUser().getAccountId());
        map.put("itemId", id);
        map.put("jmtPrice",etMoney.getText().toString());
        map.put("jmtProductCount", etNumber.getText().toString());
        map.put("jmtAppleReasonType", jmtAppleReasonType);
        map.put("jmtApplyReasonDetails", etDetail.getText().toString());
        data.setParameters(map);
        L.e("requestJson", data.toString());

        request(data, com.epfresh.api.constant.AppSupplyRouterConstant.cmd_order_supplier_jmt_save, onRequestCodeListener);
    }


    OnRequestListener<MinusDialogInfo> onRequestCodeListener = new OnRequestListener<MinusDialogInfo>() {
        @Override
        public MinusDialogInfo jsonToObj(String responseStr) {
            L.e("requestJson", responseStr);

            return new Gson().fromJson(responseStr, MinusDialogInfo.class);
        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {
            hideProgressDialog();
            toast("数据异常，请重试");

        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {
            hideProgressDialog();
            toast("数据异常，请重试");
        }

        @Override
        public void onStart(Object tag) {
            showProgressDialog();
        }
        @Override
        public void onResponse(ResponseEntity<MinusDialogInfo> response, Object tag) {
            hideProgressDialog();
            //response.getResponseElement().setFlag(true);//强制弹窗todo
            if(response.getResponseElement().isFlag()) {
                final MinusInfoDialog dialog = new MinusInfoDialog(OrderMinusActivity.this);
                dialog.setCanceledOnTouchOutside(false);
                dialog.setCancelable(false);
                dialog.setOnSureListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        dialog.dismiss();
                        Intent reback = new Intent();
                        setResult(0x003, reback);
                        finish();
                    }
                });
                dialog.show(response.getResponseElement().getSettleAmount()+"元");
            }else{
                Intent reback = new Intent();
                setResult(0x003, reback);
                finish();
            }


        }
    };

    class ReasonEntity{
        int id;
        String title;
    }
    private OnRequestListener<List<ReasonEntity>> onStringRequestListener = new OnRequestListener<List<ReasonEntity>>() {
        @Override
        public List<ReasonEntity> jsonToObj(String responseStr) {
            return new Gson().fromJson(responseStr, new TypeToken<List<ReasonEntity>>() {
            }.getType());
        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {
            hideProgressDialog();
        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {
            hideProgressDialog();
        }

        @Override
        public void onStart(Object tag) {
            showProgressDialog();
        }

        @Override
        public void onResponse(ResponseEntity<List<ReasonEntity>> response, Object tag) {
            hideProgressDialog();
            List<ReasonEntity> responseElement = response.getResponseElement();
            openSelect(responseElement);
        }
    };

    public void selectReason() {
        RequestEntitySupply<Map<String, String>> RequestEntitySupply = new RequestEntitySupply<>();
        RequestEntitySupply.setCmd(com.epfresh.api.constant.AppSupplyRouterConstant.cmd_order_supplier_jmt_reasonList);
        Map<String, String> map = new HashMap<>();
        map.put("itemId",id);
        RequestEntitySupply.setParameters(map);
        request(RequestEntitySupply, com.epfresh.api.constant.AppSupplyRouterConstant.cmd_order_supplier_jmt_reasonList, onStringRequestListener);
    }


    private ArrayList<String> options1Items = new ArrayList<String>();
    private WheelDialog pvOptions;

    public void openSelect(final List<ReasonEntity> list) {
        if (pvOptions == null) {
            pvOptions = new WheelDialog(this);
            pvOptions.setOnoptionsSelectListener(new WheelDialog.OnOptionsSelectListener() {
                @Override
                public void onOptionsSelect(int options1, int option2, int options3) {
                    ciReason.setTitleText(options1Items.get(options1).toString());
                    jmtAppleReasonType = "" + list.get(options1).id;
/*                    if(list.get(options1).id==1){
                        findViewById(R.id.ll_return).setVisibility(View.VISIBLE);
                    }else {
                        findViewById(R.id.ll_return).setVisibility(View.GONE);
                    }*/
                }
            });
        }
        options1Items.clear();
        if (list != null) {
            for(int i=0;i<list.size();i++){
                options1Items.add(list.get(i).title);
            }
            pvOptions.setPicker(options1Items);
            pvOptions.show();
        } else {
            toast("该选项没有数据");
        }

    }

}
